package 多线程和队列.辅助类JUC;


import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 孔令富  2021/12/20
 */
public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        new Thread(() -> {
            queue.writeObj("konglingfu");
        }).start();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                queue.readObj();
            },String.valueOf(i)).start();
        }
    }
}

class MyQueue {

    private Object obj;
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void readObj() {
        try {
            rwLock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+obj);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void writeObj(Object obj) {

        rwLock.writeLock().lock();

        try {
            this.obj = obj;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
    }

}
